package indexer;

import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy;
import org.apache.lucene.index.NoDeletionPolicy;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.freelunch.visitors.ClassVisitor;


public class ClassIndexer {
	private static final int BUCKET_VOLUME = 100;
	
	public static void recDir(String args) {
		Directory fdr;
		try {
			fdr = FSDirectory.open(new File("C:\\JKR\\Gunscape\\ClassIndex"));
			Analyzer standardAnalyzer = new StandardAnalyzer(Version.LUCENE_35);
			
			IndexDeletionPolicy deletionPolicy = NoDeletionPolicy.INSTANCE ;
		
			//removed due to DEPRECATION
			//IndexWriter indexWriter =new IndexWriter(fdr,standardAnalyzer,create,deletionPolicy,IndexWriter.MaxFieldLength.UNLIMITED);
			IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35,standardAnalyzer);
			indexWriterConfig.setIndexDeletionPolicy(deletionPolicy);
			IndexWriter indexWriter = new IndexWriter(fdr,indexWriterConfig);
			
			
			Stack<File> stk = new Stack<File>();
			File files = new File(args);
			stk.push(files);
			int lng =0;
			
		     while (!stk.isEmpty()) {
				// System.out.println(file);
				// if(file.isDirectory())
				// {stk.push(file);}
				File file = stk.pop();
				
				if (file.isDirectory()) {
					//System.out.println(file);
					for (File fl : file.listFiles()) {
						if (fl.isDirectory())
							{stk.push(fl);}

						if (!fl.getName().endsWith(".java"))
							{continue;}
								System.out.println(fl);
								lng=(lng+1)%BUCKET_VOLUME;
						
								 CompilationUnit cu;
								 InputStream in=new FileInputStream(fl);
								 try {									 
							            cu = JavaParser.parse(in);
							            
							             ClassVisitor.visit(cu,indexWriter,fl.getAbsolutePath());
							        } catch (ParseException e) {
										
										e.printStackTrace();
									} finally {
							            if(in!=null)
							            	in.close();
							        }

					
								
							}

						}}

			
			indexWriter.commit();
			if(indexWriter!=null)
				indexWriter.close();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
		}
public static void main(String[] args) {
	recDir("C:\\HOUSE\\E11.19\\");
}
}
